import { useLocation, useNavigate } from "react-router-dom";
import { getArticleDetail } from "@/apis/articlesApi.ts";
import { userLikeArticle, userUnLikeArticle } from "@/apis/userApi.ts";
import { useEffect, useState } from "react";
import { Space, List, message, Modal, Checkbox, Input, Button } from "antd";
import CommentRenderer from "./CommentItem"; // 导入 CommentRenderer 组件
import { addArticleViews, userAddComment } from "@/apis/articlesApi.ts";
import { StarFilled, LikeFilled, EyeFilled } from "@ant-design/icons";
import { useSelector, useDispatch } from "react-redux";
import {
  setUserLikesListToStore,
  deleteUserCollectionArticle,
  addUserCollectionArticle,
} from "@/store/UserInfo/index.ts";
import { RootState } from "@/store";
import { userDeleteFolderArticle, userAddFolderArticle } from "@/apis/userApi";
import { ArticleDetail, CollectionFolder } from "@/apis/shared";
import { formatDate } from "@/utils/tool.ts";
import "./index.scss";

function Article() {
  const location = useLocation();
  const dispatch = useDispatch();
  const navigate = useNavigate();

  // 文章详情数据
  const [article, setArticle] = useState<ArticleDetail | null>(null);

  // URLSearchParams 解析
  const searchParams = new URLSearchParams(location.search);
  // 传过来的文章的id
  const id = searchParams.get("_id");

  // 使用 useSelector 获取 userLikesList 和 userCollectionList
  const userLikesListFromStore = useSelector(
    (state: RootState) => state.UserInfoStore.userLikesList
  );
  const userCollectionListFromStore = useSelector(
    (state: RootState) => state.UserInfoStore.userCollectionList
  );

  // 文章点赞数
  const [likeCount, setLikeCount] = useState(0);

  // 初始化状态变量
  const [userLikesList, setUserLikesList] = useState(userLikesListFromStore);
  const [userCollectionList, setUserCollectionList] = useState<
    // 这个userCollectionList相当于是将用户的收藏夹保存了一份
    CollectionFolder[]
  >(userCollectionListFromStore);

  // 是否点赞
  const isLiked = (_id: string, userLikesList: string[]) => {
    return userLikesList.some((item) => item === _id);
  };
  const [isArticleLike, setIsArticleLike] = useState(
    isLiked(id!, userLikesList)
  );

  // 弹窗是否打开
  const [isModalOpen, setIsModalOpen] = useState(false);

  // 判断是否已登录
  const isLogin = useSelector(
    (state: RootState) => !!state.UserInfoStore.shortToken // 这里的 !! 是为了将 token 的值转换成 boolean 类型
  );
  const [islogin] = useState(isLogin);

  // 维护每个文件夹的选中状态
  const folderSelectionObj: { [key: string]: boolean } = {};
  const folderSelectionInit = () => {
    userCollectionList.forEach((folder) => {
      folderSelectionObj[folder.folderName] = folder.collectItem.some(
        (folderItem) => folderItem._id === id!
      );
    });

    return folderSelectionObj;
  };
  const [folderSelection, setFolderSelection] = useState<{
    [key: string]: boolean;
  }>(folderSelectionInit());

  // 弹窗显示
  const showModal = async () => {
    console.log("showModal");
    // 判断是否登录
    if (!islogin) {
      message.error("请先登录", 1, () => {
        navigate("/login");
      });

      return;
    }

    // 弹窗显示
    setIsModalOpen(true);
  };

  // 弹窗确认逻辑
  const handleOk = async () => {
    // 这里的 folderSelection 是根据 userCollectionList 的数据进行计算的
    // 所以这里是只是对 userCollectionList 的数据进行更新，没有对 folderSelection 的数据进行判断
    // 如果后面的时候出现了在这个弹窗中添加了新的收藏夹的功能，到时候就需要额外的根据 folderSelection 的数据进行维护了

    // 自己维护收藏夹列表中的文章状态
    // 对收藏夹进行遍历
    userCollectionList.forEach(async (folder) => {
      // 遍历每个收藏夹的文章列表
      if (folder.collectItem.some((item) => item._id === id!)) {
        // 说明之前的文章是存在这个收藏夹中的
        if (folderSelection[folder.folderName]) {
          // 说明现在这个文章是被选中的状态
          // 不需要进行操作
        } else {
          // 说明这个文章是没有被选中的状态
          // 从收藏夹中删除文章
          const res = await userDeleteFolderArticle(folder.folderName, id!);

          // 处理返回的结果
          if (res.code === 200) {
            // 成功删除
          }

          // 更新 redux store 中的用户的收藏夹列表
          dispatch(
            deleteUserCollectionArticle({
              folderName: folder.folderName,
              _id: id!,
            })
          );
        }
      } else {
        // 说明之前的文章是不存在这个收藏夹中的
        if (folderSelection[folder.folderName]) {
          // 说明现在这个文章是被选中的状态
          // 向收藏夹中添加文章
          const res = await userAddFolderArticle(folder.folderName, id!);

          // 处理返回的结果
          if (res.code === 200) {
            // 成功添加
          }

          // 更新 redux store 中的用户的收藏夹列表
          dispatch(
            addUserCollectionArticle({
              folderName: folder.folderName,
              _id: id!,
              summary: article?.summary!,
              title: article?.title!,
            })
          );
        } else {
          // 说明这个文章是没有被选中的状态
          // 不需要进行操作
        }
      }
    });

    // 重新设置一下这个 userCollectionList 的数据
    setUserCollectionList([...userCollectionListFromStore]);

    // 关闭弹窗
    setIsModalOpen(false);
  };

  // 弹窗取消逻辑
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 判断是否收藏
  const isStared: () => boolean = () => {
    let isStaredFlag = false;
    userCollectionList.forEach((folder) => {
      if (folder.collectItem.some((item) => item._id === id)) {
        isStaredFlag = true;
      }
    });

    return isStaredFlag;
  };

  // 判断文章是否被收藏
  const [isStaredFlag, setIsStaredFlag] = useState(isStared());

  useEffect(() => {
    let newIsStared = false;

    userCollectionListFromStore.forEach((folder) => {
      if (folder.collectItem.some((item) => item._id === id)) {
        newIsStared = true;
      }
    });

    setIsStaredFlag(newIsStared);
  }, [userCollectionListFromStore]);

  // 获取文章详情
  const fetchData = async () => {
    // 判断是否有文章的id
    if (!id) return;

    // 获取文章详情
    const res = await getArticleDetail(id);

    // 设置文章的详情数据
    setArticle(res.data || null);

    // 这是文章的点赞数
    setLikeCount(res.data?.likes || 0);

    if (res.code === 200) {
      // 如果成功返回就增加文章的阅读数
      await addArticleViews(id);
    }
  };

  // 页面加载完成后，获取文章详情
  useEffect(() => {
    fetchData();
  }, [id]);

  // 点赞逻辑
  const handleLikeClick = async (_id: string) => {
    console.log("Clicked like");

    // 判断是否点过赞了
    if (isLiked(_id, userLikesList)) {
      // 点过赞了，取消点赞
      const res = await userUnLikeArticle(_id);

      // 处理后端返回的结果
      if (res.code !== 200) {
        return message.error("取消点赞失败");
      }

      // 取消点赞，更新用户的点赞列表
      setUserLikesList((prevLikesList) => {
        return prevLikesList.filter((item) => item !== _id);
      });

      // 更新文章的点赞数
      setLikeCount((prevLikeCount) => prevLikeCount - 1);

      // 更新 redux store 中的用户的点赞列表
      dispatch(
        setUserLikesListToStore(userLikesList.filter((item) => item !== _id))
      );
      setIsArticleLike(false);
    } else {
      console.log("在未点赞这里", userLikesList);
      // 未点过赞，点赞
      const res = await userLikeArticle(_id);

      // 处理后端返回的结果
      if (res.code !== 200) {
        return message.error("点赞失败");
      }

      // 点赞，更新用户的点赞列表
      setUserLikesList((prevLikesList) => {
        return [...prevLikesList, _id];
      });

      // 更新文章的点赞数
      setLikeCount((prevLikeCount) => prevLikeCount + 1);

      // 更新 redux store 中的用户的点赞列表
      dispatch(setUserLikesListToStore([...userLikesList, _id]));
      setIsArticleLike(true);
    }
  };

  // 收藏逻辑
  const handleStarClick = async () => {
    console.log("收藏了");

    // 展示收藏夹弹窗
    showModal();
  };

  // 处理Checkbox的变化
  const handleCheckboxChange = (folderName: string, checked: boolean) => {
    setFolderSelection((prevSelection) => ({
      ...prevSelection,
      [folderName]: checked,
    }));
  };

  // 文章评论内容
  const [commentContent, setCommentContent] = useState("");

  // 发布评论
  const handleCommentSubmit = async () => {
    // 判断是否登录
    if (!islogin) {
      message.error("请先登录", 1, () => {
        navigate("/login");
      });

      return;
    }

    // 判断评论的内容是否为空
    if (!commentContent) {
      message.error("评论内容不能为空");
      return;
    }

    // 发送请求
    const res = await userAddComment(id!, commentContent);

    // 处理后端返回的结果
    if (res.code !== 200) {
      return message.error("评论失败");
    }

    // 清空评论的内容
    setCommentContent("");

    // 修改文章的数据
    setArticle((prevArticle) => {
      if (!prevArticle) return prevArticle;

      return {
        ...prevArticle,
        commentList: [...res.data!],
      };
    });
  };

  return (
    <div style={{ maxWidth: "1000px", margin: "0 auto", width: "90%" }}>
      <Space direction="vertical" style={{ width: "100%", maxWidth: "1200px" }}>
        <h1>{article?.title}</h1>

        {/* 文章简要信息 */}
        <div
          style={{
            backgroundColor: "#f0f2f5",
            padding: "10px",
            margin: "0px 0px 15px 0px",
          }}
        >
          <span>
            {" "}
            <a href={`/layout/author?authorEmail=${article?.authorEmail}`}>
              {article?.authorNickName || article?.authorEmail}
            </a>{" "}
          </span>{" "}
          <span>于 {formatDate(article?.createTime!)} 发布 </span>{" "}
          <span>
            <EyeFilled style={{ color: "gray" }} /> {article?.views}
          </span>{" "}
          <span>
            点赞{" "}
            <LikeFilled
              style={{ color: isArticleLike ? "red" : "gray" }}
              onClick={() => handleLikeClick(article?._id!)}
            />
            {likeCount}
          </span>{" "}
          <span>
            收藏{" "}
            <StarFilled
              style={{ color: isStaredFlag ? "red" : "gray" }}
              onClick={() => handleStarClick()}
            />
          </span>{" "}
        </div>

        {/* 文章摘要 */}
        <div style={{ backgroundColor: "#f5f5f5" }}>
          文章简要：
          <p>{article?.summary}</p>
        </div>

        {/* 文章内容 */}
        <Space>
          <div
            className="article-container"
            style={{ width: "100%", margin: "0 auto" }}
            dangerouslySetInnerHTML={{
              __html: article?.content || "",
            }}
          />
        </Space>

        {/* 评论列表 */}
        <div>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              width: "100%",
              marginBottom: "30px",
            }}
          >
            <div style={{ flex: 6, marginRight: "10px" }}>
              <Input.TextArea
                autoSize={{ minRows: 1, maxRows: 10 }}
                value={commentContent}
                onChange={(e) => setCommentContent(e.target.value)}
                placeholder="请输入评论内容"
              />
            </div>
            <div style={{ flex: 2 }}>
              <Button type="primary" onClick={handleCommentSubmit}>
                添加评论
              </Button>
            </div>
          </div>

          <List>
            {article?.commentList?.map((comment) => (
              <div key={comment._id}>
                <CommentRenderer
                  article={article}
                  setArticle={setArticle}
                  comment={comment}
                  level={0}
                />
              </div>
            ))}
          </List>
        </div>

        {/* 收藏夹弹窗 */}
        <Modal
          title="收藏文章"
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <List
            size="small"
            bordered
            dataSource={userCollectionList}
            renderItem={(item) => (
              <List.Item>
                <span>{item.folderName}</span>{" "}
                <Checkbox
                  checked={folderSelection[item.folderName]}
                  onChange={(e) =>
                    handleCheckboxChange(item.folderName, e.target.checked)
                  }
                />
              </List.Item>
            )}
          />
        </Modal>
      </Space>
    </div>
  );
}

export default Article;
